﻿Imports System.IO
Imports SACommon

Public Class Settings
    Private mItems As Dictionary(Of Integer, Object)
    Private mFilename As String
#Region "Get Properties"
    ReadOnly Property GetValue(Key As Integer) As Object
        Get
            If mItems.ContainsKey(Key) = True Then Return mItems(Key)
            Return Nothing
        End Get
    End Property
    ReadOnly Property ValueList() As Dictionary(Of Integer, Object)
        Get
            Return mItems
        End Get
    End Property
    ReadOnly Property IsSettingsFile() As Boolean
        Get
            Using sf As New StripeFile
                Return sf.IsStripeFile(mFilename)
            End Using
        End Get
    End Property
#End Region
    Sub New(FileName As String)
        mItems = New Dictionary(Of Integer, Object)
        If FileName.Trim <> "" Then
            mFilename = FileName
            If IsSettingsFile = False Then If File.Exists(FileName) Then File.Delete(mFilename)
            If File.Exists(mFilename) = False Then SaveFile()
            Dim tResult = ReadFile()
            If tResult.Result <> SAEventArgs.Results.Success Then mItems = New Dictionary(Of Integer, Object)
        End If
    End Sub
    Sub Add(Key As Integer, Value As Object)
        Dim x = Value.GetType
        If mItems.ContainsKey(Key) = False Then
            mItems.Add(Key, Value)
        Else
            mItems(Key) = Value
        End If
    End Sub
    Sub RemoveItem(Key As Integer)
        mItems.Remove(Key)
    End Sub
    Sub SaveFile()
        Using sf As New StripeFile
            For Each item In mItems
                sf.Add(item.Key)
                sf.Add(item.Value)
                sf.AddLine()
            Next
            sf.SaveFile(mFilename, True)
        End Using
    End Sub
    Function ReadFile() As SAEventArgs
        mItems = New Dictionary(Of Integer, Object)
        Using sf As New StripeFile
            Dim tResult = sf.ReadFile(mFilename)
            If tResult.Result <> SAEventArgs.Results.Success Then Return tResult
            Dim t As Integer = sf.LineItemCount
            'If t > 0 Then
            For i = 0 To t - 1
                mItems.Add(sf.GetLineItems(i, 0), sf.GetLineItems(i, 1))
            Next
            'End If
        End Using
        Return New SAEventArgs("", SAEventArgs.Results.Success)
    End Function
End Class
